package com.jie.client.service.ui.view;

import com.jie.client.core.ClientApplication;
import com.jie.client.core.handler.ClientWriteHandler;
import com.jie.client.service.ui.constant.ViewMapConstant;
import com.jie.client.service.ui.view.cell.GroupListCell;
import com.jie.client.service.ui.view.item.GroupItem;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.util.HashMap;
import java.util.Map;

/**
 * 所有群的视图
 * @author XieZhiJie
 * @date 2022/04/29 10:31
 */
public class AllGroupView {

    private final Stage stage = new Stage();

    /**
     * 展示所有群组的列表
     */
    public final ListView<GroupItem> allGroupView = new ListView<>();

    public void createAllGroupView() {
        ClientApplication.VIEW_MAP.put(ViewMapConstant.ALL_GROUP_VIEW, this);
        // 总Box
        VBox allGroupBox = new VBox();

        this.allGroupView.setEditable(false);
        // 设置列表怎么展示
        this.allGroupView.setCellFactory(param -> new GroupListCell());
        this.allGroupView.setOnMouseClicked(this::onAddAction);

        // 总布局
        allGroupBox.getChildren().add(this.allGroupView);

        allGroupBox.setPadding(new Insets(10, 5, 10, 5));

        Scene scene = new Scene(allGroupBox, 300, 450);
        this.stage.setOnCloseRequest(event -> ClientApplication.VIEW_MAP.remove(ViewMapConstant.ALL_GROUP_VIEW));
        this.stage.setTitle("双击入群");
        this.stage.setScene(scene);
        this.stage.show();

        // 尝试在这里发送请求
        Map<String, Object> map = new HashMap<>(2);
        map.put("choice", "getGroupList");
        ClientWriteHandler.sendRequest(map);
    }

    private void onAddAction(MouseEvent event) {
        if (event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2) {
            ObservableList<GroupItem> groupData = this.allGroupView.getItems();
            int index = this.allGroupView.getSelectionModel().getSelectedIndex();
            GroupItem groupItem;
            try {
                groupItem = groupData.get(index);
            } catch (ArrayIndexOutOfBoundsException e) {
                return;
            }
            Map<String, Object> map = new HashMap<>(2);
            map.put("choice", "joinGroup");
            map.put("groupId", groupItem.getGroupId());
            ClientWriteHandler.sendRequest(map);
        }
    }

}
